package com.raos.code.config;

import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

/**
 * EasyCaptcha 配置（错误的尝试--只能生成一个相同的验证码--单例的，不保证）
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/3/23 21:38
 */
@Configuration
public class CaptchaConfig {

    @Value("${captcha.className:'com.wf.captcha.SpecCaptcha'}")
    private String className;
    @Value("${captcha.img.width:'100'}")
    private int imgWidth;
    @Value("${captcha.img.height:'42'}")
    private int imgHeight;
    @Value("${captcha.char.type:'6'}")
    private int charType;
    @Value("${captcha.char.length:'4'}")
    private int charLength;

    @Scope("prototype")
    @Bean
    public Captcha captcha() {
        Captcha captcha = null;
        // 默认的png验证码
        if ("com.wf.captcha.SpecCaptcha".equals(className)) {
            captcha = new SpecCaptcha(imgWidth, imgHeight, charLength);
            captcha.setCharType(charType);
        }
        // 动态gif验证码
        else if ("com.wf.captcha.GifCaptcha".equals(className)) {
            captcha = new GifCaptcha(imgWidth, imgHeight, charLength);
            captcha.setCharType(charType);
        }
        // 算术png验证码(算术验证码的len表示是几位数运算，而其他验证码的len表示验证码的位数)
        else if ("com.wf.captcha.ArithmeticCaptcha".equals(className)) {
            if (charLength > 3 && charLength < 6) {
                charLength = charLength - 2;
            } else {
                charLength = 2;
            }
            captcha = new ArithmeticCaptcha(imgWidth, imgHeight, charLength);
        }
        // 中文png验证码
        else if ("com.wf.captcha.ChineseCaptcha".equals(className)) {
            captcha = new ChineseCaptcha(imgWidth, imgHeight, charLength);
        }
        // 中文gif验证码
        else if ("com.wf.captcha.ChineseGifCaptcha".equals(className)) {
            captcha = new ChineseGifCaptcha(imgWidth, imgHeight, charLength);
        }

        Assert.isTrue(!ObjectUtils.isEmpty(captcha), "验证码组件初始化失败");

        return captcha;
    }


}
